# coding:utf-8

import re
import os
import time
import hashlib
import string
import zipfile
import subprocess
import socket

WK_PATH = os.path.split(__file__)[0]

def to_integer(raw=None, max=None, default=0):
    '''
    将输入转换为整数
    参数：
        raw String/Integer 输入
        max Integer 最大值
        default Integer 默认值/失败后的输出
    输出：
        Integer

    '''
    # 检验输入
    if not raw:
        return 0
    else:
        pass

    # 判断输入是否整数
    if not isinstance(raw, int):
        try:
            # 如果输入不是整数，尝试转换
            raw = int(raw)
        except:
            # 如果转换失败，返回默认值
            return default
    else:
        pass

    # 如果存在最大值限制，则进一步判断
    if bool(max):
        # 判断输入是否达到上限
        if raw < max:
            return raw
        # 若达到上限，则返回上限
        else:
            return max
    else:
        return raw


def is_mail_address(raw=None):
    """
    校验邮件地址是否正确
    ->
        @raw String
    <-
        Bool
    """

    # 检验输入
    if not raw:
        return False
    else:
        pass

    # 使用正则表达式匹配"aaa@bbb.ccc"的字符串
    r = re.compile(r'\w+@\w+\.\w+')
    if not bool(r.search(raw)):
        return False
    else:
        return True



def is_domain(raw=None):
    """
    检查一个字符串是否为域名
    ->
        @raw String
    <-
        Bool
    """

    # 检验输入
    if not raw:
        return False
    else:
        pass

    # 使用正则表达式匹配"bbb.ccc"的字符串
    r = re.compile(r'\w+\.\w+')
    if not bool(r.search(raw)):
        return False
    else:
        valid_letters = string.ascii_letters + string.digits + "-."
        for l in raw:
            if l not in valid_letters:
                return False
        return True


def timestamp_13():

    """
    获取当前 13 位时间戳
    ->
        None
    <-
        timestamp[:12]
    """
    
    return round(time.time()*1000)

def timestamp():

    """
    获取当前 11 位时间戳
    ->
        None
    <-
        timestamp[:10]
    """
    
    return round(time.time())
    
    
def str_time_list(ts=None):

    """
    时间戳转换为可读时间列表
    ->
        @ts Int
            未指定 ts 时，生成当前时间
    <-
        List
    """

    if not ts:
        ts = timestamp()
    else:
        pass

    t = time.localtime(timestamp())
    return [t.tm_year,t.tm_mon,t.tm_mday,t.tm_hour,t.tm_min,t.tm_sec,t.tm_yday]



def to_md5(raw=None, mix_text=None):
    
    """
    计算字符串的 md5
    ->
        @raw String
        @mix_text String
    <-
        String
    """
    if not raw:
        raw = timestamp_13()
    else:
        pass

    t = str(raw)

    if bool(mix_text):
        t = str(mix_text) + t
    else:
        pass

    return hashlib.md5(t.encode(encoding="UTF-8")).hexdigest()


def timer(function):
    """
    计时装饰器
    ->
        @function function
    <-
        None
    """
    def d():
        t1 = time.time()
        function()
        print((time.time() - t1)*1000)
    return d


def extract_zip_to_dir(zip_file_path=None, target_dir_path=None):
    """
    解压 zip 文件到指定文件夹
    """
    try:
        with zipfile.ZipFile(zip_file_path, "r") as zip_ref:
            zip_ref.extractall(target_dir_path)
        return True
    except:
        return False


def create_zip_from_dir(dir_path=None, zip_file_path=None):
    """
    为文件夹创建 zip 归档
    """
    try:
        # 检查文件是否存在
        if os.path.isfile(zip_file_path):
            # 目标位置被占用
            return False
        else:
            pass
        
        with zipfile.ZipFile(zip_file_path, "w") as zip_ref:
            for root, dirs, files in os.walk(dir_path):
                for f in files:
                    zip_ref.write(os.path.join(root, f))
        return True
    except:
        return False


def shell(cmd):
    """后台执行命令行"""
    return subprocess.getstatusoutput(cmd)


def get_ip_by_domain(domain):
    """获取域名指向的 ip 地址"""
    return socket.gethostbyname(domain)


def get_host_ip():
    """获取本机活跃 ip"""
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip


